import { HttpException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserInfoDto } from 'src/userInfo/dto/userinfo.dto';
import { UserInfo } from 'src/userInfo/entities/userinfo.entity';
import { UserInfoService } from 'src/userInfo/userinfo.service';
import * as svgCaptcha from 'svg-captcha';

@Injectable()
export class AuthService {
  constructor(
    @InjectModel('UserInfos') private readonly userInfoModel: Model<UserInfo>,
    private jwtService: JwtService,
  ) {}
  async login(userInfoDto: UserInfoDto): Promise<any> {
    const obj = await this.userInfoModel.findOne({
      account: userInfoDto.account,
      password: userInfoDto.password,
    });
    if (!!obj) {
      const token = this.jwtService.sign(
        {
          username: obj.account,
          password: obj.password,
        },
        {
          privateKey: 'blackbox',
        },
      );
      return {
        token: `Bearer ${token}`,
        userInfo: obj,
      };
    } else {
      throw new HttpException('账号/密码错误', 500);
    }
  }

  async getInfo(userInfoDto: UserInfoDto) {
    const obj = await this.userInfoModel.findOne({
      id: userInfoDto.id,
    });
    if (!!obj) {
      return obj;
    } else {
      throw new HttpException('获取用户信息失败', 500);
    }
  }

  getCode() {
    const r = (Math.random() * 255).toFixed();
    const g = (Math.random() * 255).toFixed();
    const b = (Math.random() * 255).toFixed();
    const o = Math.random().toFixed(2);
    const s = svgCaptcha.create({
      size: 1, //生成几个验证码
      fontSize: 50, //文字大小
      width: 100, //宽度
      height: 34, //高度
      background: `rgba(${r},${g},${b},${o})`, //背景
    });
    return s;
  }
}
